use std::fmt::{Display, Formatter};

#[derive(Debug)]
pub enum ServerError {
    ///常规异常
    Message(String),
    IoError(String),
    DbError(String),
    SqlxError(sqlx::Error),
}
impl Display for ServerError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ServerError::Message(msg) => {
                write!(f, "通用异常: {}", msg)
            }
            ServerError::IoError(msg) => {
                write!(f, "IO异常: {}", msg)
            }
            ServerError::DbError(error) => {
                write!(f, "IO异常: {:?}", error)
            }
            ServerError::SqlxError(error) => {
                write!(f, "IO异常: {:?}", error)
            }
        }
    }
}

impl std::error::Error for ServerError {}

impl From<sqlx::Error> for ServerError {
    fn from(value: sqlx::Error) -> Self {
        ServerError::SqlxError(value)
    }
}

// we must manually implement serde::Serialize
impl serde::Serialize for ServerError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::ser::Serializer,
    {
        serializer.serialize_str(self.to_string().as_ref())
    }
}

